package com.lxz.jucdemo.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: 刘新智
 * @Date: 2025/10/25 11:38
 * @Description:
 * @Version: v1.0
 */
public class LockTest {
    public static void main(String[] args) {
        ticket2 t = new ticket2();
        new Thread(()->{
            for (int i = 0; i < 15; i++) {
                t.sale();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 15; i++) {
                t.sale();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 15; i++) {
                t.sale();
            }
        },"C").start();

    }
}

class ticket2{
    private int number = 30;

    Lock lock = new ReentrantLock();

    public void sale(){
        lock.lock();
        try{
            if(number > 0){
                System.out.println(Thread.currentThread().getName() + "卖出了第" + (number--) + "张票，剩余：" + number);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }
    }
}
